﻿using Fantasy;
using Fantasy.Async;
using Fantasy.Network;
using Fantasy.Network.Interface;
using Fantasy.Platform.Net;

namespace Entity.Handler.CustomRouteHandler;

/// <summary>
/// 客户端-> gate-> chat
/// 由gate服务器发起的和chat服务器之间的第一次连接
/// 创建中转路由
/// </summary>
public class C2G_ConnectChatRequestHandler : MessageRPC<C2G_ConnectChatRequest1, G2C_ConnectChatResponse1>
{
    protected override async FTask Run(Session session, C2G_ConnectChatRequest1 request, G2C_ConnectChatResponse1 response, Action reply)
    {
        var chatScene = SceneConfigData.Instance.GetSceneBySceneType(SceneType.Chat);
        SceneConfig chatSceneConfig = chatScene[0];
        var sceneNetworkMessagingComponent = session.Scene.NetworkMessagingComponent;
        //客户端-->gate-->chat
        Chat2G_ConnectResponse chatRsp =
            (Chat2G_ConnectResponse)await sceneNetworkMessagingComponent.CallInnerRoute(chatSceneConfig.RouteId,
                new G2Chat_ConnectRequest() { });
        if (chatRsp.ErrorCode != 0)
        {
            Log.Error($"{chatRsp.ErrorCode}");
            return;
        }
        Log.Debug($"接收到Chat的RouteId: {chatRsp.routeId}");
        RouteComponent routeComponent = session.GetOrAddComponent<RouteComponent>();
        routeComponent.AddAddress(RouteType.ChatRoute, chatRsp.routeId);
    }
}
